﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Altairis.MailToolkit.ListManager.Pages {
    public partial class HomePage : System.Web.UI.Page {

        protected void Page_Init(object sender, EventArgs e) {
            // Populate dropdown with mailing list names
            foreach (MailingListProvider list in MailingListManager.Lists) {
                this.ListName.Items.Add(new ListItem(list.Description, list.Name));
            }
        }

        protected void SubmitButton_Click(object sender, EventArgs e) {
            // Validate arguments
            if (!this.IsValid) return;

            // Parse e-mail address
            var email = new MailAddress(this.EmailAddressTextBox.Text);

            // Get base URL
            var baseUrl = new UriBuilder(this.Request.Url) {
                Path = string.Empty,
                Query = string.Empty
            };

            if (this.ListOperation.SelectedValue.Equals("SUB")) {
                // Subscribe
                var result = MailingListManager.Subscribe(this.ListName.SelectedValue, email, baseUrl);
                if (result) {
                    this.LiteralMessage.Text = string.Format(Resources.UI.MsgSubConfirmReq, email.Address);
                }
                else {
                    this.LiteralMessage.Text = string.Format(Resources.UI.MsgSubAlready, email.Address);
                }
            }
            else {
                // Remove
                var result = MailingListManager.Remove(this.ListName.SelectedValue, email, baseUrl);
                if (result) {
                    this.LiteralMessage.Text = string.Format(Resources.UI.MsgRemConfirmReq, email.Address);
                }
                else {
                    this.LiteralMessage.Text = string.Format(Resources.UI.MsgRemAlready, email.Address);
                }
            }

            // Display result
            this.MultiViewPage.SetActiveView(this.ViewMessage);
        }

        protected void BackButton_Click(object sender, EventArgs e) {
            Response.RedirectToRoute("HomePage");
        }

    }
}